<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${empty vehicle ? '添加' : '编辑'}车辆信息</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
  <link rel="stylesheet" href="${pageContext.request.contextPath}/css/purchase.css">
  <style>
    .form-container {
      max-width: 700px;
      margin: 0 auto;
      background: white;
      border-radius: 10px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.05);
      padding: 25px;
    }
    .preview-img {
      max-width: 100%;
      height: 200px;
      object-fit: contain;
      border: 1px dashed #ced4da;
      border-radius: 5px;
      padding: 10px;
      display: ${not empty vehicle.pic ? 'block' : 'none'};
    }
    .upload-area {
      border: 2px dashed #dee2e6;
      border-radius: 8px;
      padding: 20px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s ease;
      background-color: #f8f9fa;
    }
    .upload-area:hover {
      border-color: #0d6efd;
      background-color: #e9f0ff;
    }
    .upload-icon {
      font-size: 3rem;
      color: #6c757d;
    }
    .form-header {
      border-bottom: 2px solid #f0f0f0;
      padding-bottom: 15px;
      margin-bottom: 25px;
    }
    .default-img {
      background-color: #f8f9fa;
      border: 1px dashed #dee2e6;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #6c757d;
      height: 200px;
      margin-bottom: 15px;
    }
  </style>
</head>
<body>
<!-- 顶部导航 -->
<header class="dashboard-header">
  <div class="container">
    <div class="d-flex justify-content-between align-items-center">
      <div>
        <h1 class="h3 mb-0"><i class="bi bi-bicycle"></i> 电动车销售管理系统</h1>
        <p class="mb-0 opacity-75">业务员工作台</p>
      </div>
      <div class="d-flex align-items-center">
        <div class="me-3">
          <span class="d-none d-md-inline">${currentUser.name}</span>
          <div class="badge bg-light text-dark">
            <i class="bi bi-person-circle me-1"></i> 业务员
          </div>
        </div>
        <div class="dropdown">
          <button class="btn btn-light rounded-circle p-1" type="button" data-bs-toggle="dropdown">
            <i class="bi bi-gear fs-5"></i>
          </button>
          <ul class="dropdown-menu dropdown-menu-end">
            <li><a class="dropdown-item" href="${pageContext.request.contextPath}/changePassword"><i class="bi bi-lock me-2"></i> 修改密码</a></li>
            <li><hr class="dropdown-divider"></li>
            <li><a class="dropdown-item text-danger" href="logout"><i class="bi bi-box-arrow-right me-2"></i> 退出登录</a></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</header>

<div class="container py-4">
  <!-- 面包屑导航 -->
  <nav aria-label="breadcrumb" class="mb-4">
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="${pageContext.request.contextPath}/vehicle/list">车辆管理</a></li>
      <li class="breadcrumb-item active" aria-current="page">${empty vehicle ? '添加' : '编辑'}车辆</li>
    </ol>
  </nav>

  <div class="form-container">
    <div class="form-header">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <h2 class="mb-0"><i class="bi bi-bicycle me-2"></i>${empty vehicle ? '添加' : '编辑'}车辆信息</h2>
          <p class="text-muted mb-0">${empty vehicle ? '创建' : '更新'}电动车详细信息</p>
        </div>
        <div>
          <a href="${pageContext.request.contextPath}/vehicle/list" class="btn btn-light">
            <i class="bi bi-arrow-left me-1"></i> 返回列表
          </a>
        </div>
      </div>
    </div>

    <!-- 错误消息提示 -->
    <c:if test="${not empty errorMessage}">
      <div class="alert alert-danger alert-dismissible fade show mb-4" role="alert">
        <i class="bi bi-exclamation-triangle me-2"></i> ${errorMessage}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
      </div>
    </c:if>

    <form action="${pageContext.request.contextPath}/vehicle/${empty vehicle ? 'save' : 'update'}"
          method="post" enctype="multipart/form-data" id="vehicleForm">

      <c:if test="${not empty vehicle}">
        <input type="hidden" name="id" value="${vehicle.id}">
      </c:if>

      <div class="mb-4">
        <label for="brand" class="form-label">品牌 <span class="text-danger">*</span></label>
        <input type="text" class="form-control" id="brand" name="brand"
               value="${vehicle.brand}" required placeholder="输入车辆品牌">
      </div>

      <div class="mb-4">
        <label for="model" class="form-label">型号 <span class="text-danger">*</span></label>
        <input type="text" class="form-control" id="model" name="model"
               value="${vehicle.model}" required placeholder="输入车辆型号">
      </div>

      <div class="mb-4">
        <label for="color" class="form-label">颜色 <span class="text-danger">*</span></label>
        <input type="text" class="form-control" id="color" name="color"
               value="${vehicle.color}" required placeholder="输入车辆颜色">
      </div>

      <div class="row mb-4">
        <div class="col-md-6">
          <label for="productionYear" class="form-label">生产年份 <span class="text-danger">*</span></label>
          <select class="form-select" id="productionYear" name="productionYear" required>
            <option value="">选择生产年份</option>
            <c:forEach var="year" begin="2020" end="2025">
              <option value="${year}" ${vehicle.productionYear == year ? 'selected' : ''}>
                  ${year}年
              </option>
            </c:forEach>
          </select>
        </div>
        <div class="col-md-6">
          <label for="price" class="form-label">价格 (元) <span class="text-danger">*</span></label>
          <div class="input-group">
            <span class="input-group-text">¥</span>
            <input type="number" class="form-control" id="price" name="price"
                   value="${vehicle.price}" step="0.01" min="0" required placeholder="0.00">
          </div>
        </div>
      </div>

      <div class="mb-4">
        <label class="form-label">车辆图片</label>

        <c:if test="${not empty vehicle}">
          <div class="mb-3 text-center">
            <c:choose>
              <c:when test="${not empty vehicle.pic}">
                <img src="${pageContext.request.contextPath}/images/vehicles/${vehicle.pic}"
                     class="preview-img mb-3" id="previewImage"
                     alt="${vehicle.brand} ${vehicle.model}">
              </c:when>
              <c:otherwise>
                <div class="default-img" id="previewImage">
                  <i class="bi bi-bicycle fs-1"></i>
                </div>
              </c:otherwise>
            </c:choose>
          </div>
        </c:if>

        <div class="upload-area" id="uploadArea">
          <div class="upload-icon mb-2">
            <i class="bi bi-cloud-arrow-up"></i>
          </div>
          <p class="mb-1">点击或拖拽图片到此处上传</p>
          <p class="small text-muted mb-0">支持 JPG, PNG 格式，最大 10MB</p>
          <input type="file" class="d-none" id="pic" name="pic" accept="image/*">
        </div>
      </div>

      <div class="d-flex justify-content-end mt-5 pt-3 border-top">
        <button type="submit" class="btn btn-primary px-4 py-2">
          <i class="bi bi-save me-2"></i> ${empty vehicle ? '添加车辆' : '更新信息'}
        </button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
  // 图片上传功能
  const uploadArea = document.getElementById('uploadArea');
  const fileInput = document.getElementById('pic');
  let previewImage = document.getElementById('previewImage');

  // 点击上传区域触发文件选择
  uploadArea.addEventListener('click', () => {
    fileInput.click();
  });

  // 拖拽效果处理
  uploadArea.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadArea.classList.add('bg-primary-subtle');
  });

  uploadArea.addEventListener('dragleave', () => {
    uploadArea.classList.remove('bg-primary-subtle');
  });

  uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.classList.remove('bg-primary-subtle');

    if (e.dataTransfer.files.length) {
      fileInput.files = e.dataTransfer.files;
      previewFile(e.dataTransfer.files[0]);
    }
  });

  // 文件选择变化处理
  fileInput.addEventListener('change', (e) => {
    if (e.target.files.length) {
      previewFile(e.target.files[0]);
    }
  });

  // 预览图片文件
  function previewFile(file) {
    if (file && file.type.startsWith('image/')) {
      const reader = new FileReader();

      reader.onload = function(e) {
        // 如果预览图片元素不存在，则创建它
        if (!previewImage) {
          const img = document.createElement('img');
          img.id = 'previewImage';
          img.className = 'preview-img mb-3';
          img.alt = '车辆图片预览';
          uploadArea.parentNode.insertBefore(img, uploadArea);
          previewImage = img; // 更新变量引用
        }

        // 如果预览区域是div，替换为img
        if (previewImage.tagName === 'DIV') {
          const img = document.createElement('img');
          img.id = 'previewImage';
          img.className = 'preview-img mb-3';
          img.alt = '车辆图片预览';
          previewImage.parentNode.replaceChild(img, previewImage);
          previewImage = img;
        }

        previewImage.src = e.target.result;
        previewImage.style.display = 'block';
      }

      reader.readAsDataURL(file);
    } else {
      alert('请选择图片文件 (JPG, PNG)');
      fileInput.value = '';
    }
  }

  // 表单验证
  document.getElementById('vehicleForm').addEventListener('submit', function(e) {
    const price = document.getElementById('price').value;

    // 价格验证
    if (parseFloat(price) <= 0) {
      e.preventDefault();
      alert('价格必须大于0！');
      document.getElementById('price').focus();
      return false;
    }

    // 品牌验证
    const brand = document.getElementById('brand').value.trim();
    if (brand.length < 2) {
      e.preventDefault();
      alert('品牌名称至少需要2个字符！');
      document.getElementById('brand').focus();
      return false;
    }

    return true;
  });

  // 消息自动消失
  setTimeout(() => {
    const messages = document.querySelectorAll('.message');
    messages.forEach(msg => {
      msg.style.opacity = '0';
      setTimeout(() => msg.style.display = 'none', 300);
    });

    // 发送 AJAX 请求，通知服务器清空消息
    fetch('${pageContext.request.contextPath}/ClearMessageServlet', {
      method: 'GET',
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    });
  }, 3000);
</script>
</body>
</html>